/**
 * 
 */
package se.thoka.twt.client.utils;


import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;

/**
 * @author Thobias Karlsson, Thoka
 * @since 9 jan 2010
 */
public class Delayer {

	private final Timer timer;
	private int delayMillis;
	private Command delayedCommand;
	
	/**
	 * Creates a new instance of {@link Delayer}.
	 * @param delayMillis The delay in milliseconds
	 * @param delayedCommand The delayed command
	 */
	public Delayer(int delayMillis, Command delayedCommand) {
		this.delayMillis = delayMillis;
		this.delayedCommand = delayedCommand;
		
		if (delayedCommand == null) {
			TWTLogger.log(TWTLogLevel.WARNING, getClass().getName() + " delayed command is null");
		}
		
		this.timer = new Timer() {
			@Override
			public void run() {
				executeCommand();
			}
		};
	}
	
	/**
	 * Activates the delay. Prior delays will be aborted.
	 */
	public void delay() {
		if (delayMillis > 0) {
			timer.schedule(delayMillis);
		} else {
			timer.run();
		}
	}
	
	/**
	 * @return The delay in milliseconds
	 */
	public int getDelay() {
		return delayMillis;
	}
	
	/**
	 * @param delayMillis The delay in milliseconds
	 */
	public void setDelay(int delayMillis) {
		this.delayMillis = delayMillis;
	}
	
	/**
	 * Executes the delayed command
	 */
	public void executeCommand() {
		if (delayedCommand != null) {
			delayedCommand.execute();
		}
	}
}
